import 'package:flutter/material.dart';

import '../../entity/result.dart';
import '../../entity/type.dart';
import '../../util/network.dart';

class TypePage extends StatefulWidget {
  const TypePage({Key? key}) : super(key: key);

  @override
  State<TypePage> createState() => _TypePageState();
}

class _TypePageState extends State<TypePage> {

  var titleText = TextEditingController();
  var parentText = TextEditingController();

  List<dynamic> listItem = [];
  int currentItem = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getItemData();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text("返回"),
        ),
        appBar: AppBar(title: const Text("创建类别"),),
        body: Card(
          margin: const EdgeInsets.all(10.0),
          child: Column(
            children: [
              Expanded(
                flex: 1,
                child: TextField(
                  controller: titleText,
                  textInputAction: TextInputAction.next,
                  decoration: const InputDecoration(
                      hintText: "请输入标题", border: OutlineInputBorder()),
                ),
              ),
              Expanded(
                  flex: 1,
                  child: DropdownButton<dynamic>(
                    hint: const Text("请选择分区"),
                    items: getItem(),
                    value: currentItem,
                    onChanged: (value) {
                      setState(() {
                        currentItem = value;
                      });
                    },
                  )),
              Expanded(
                flex: 1,
                child: ElevatedButton(
                    onPressed: () {
                      submit();
                      Navigator.pop(context);
                    },
                    child: const Text("提交")),
              ),
            ],
          ),
        )
      ),
    );
  }

  getItem() {
    return listItem
        .map((e) => DropdownMenuItem(value: e.id, child: Text(e.name)))
        .toList();
  }

  getItemData() async {
    listItem = await getListAPI(TypeBean(), API.selectTypeList, {});
    setState(() {
      currentItem = listItem[0].id;
    });
  }

  submit() async {
    Map<String, dynamic> data = {};
    data["name"] = titleText.text;
    data["parentId"] = currentItem;
    Result result = await postAPI(API.createType, data);
  }

}
